package com.gc.web.controller.business;

import cn.hutool.core.date.DateUtil;
import com.gc.business.domain.*;
import com.gc.business.service.*;
import com.gc.common.annotation.Log;
import com.gc.common.base.Result;
import com.gc.common.enums.BusinessType;
import com.gc.common.support.Convert;
import com.gc.common.utils.MoneyUtils;
import com.gc.common.utils.StringUtils;
import com.gc.common.utils.poi.ExcelUtil;
import com.gc.framework.util.ShiroUtils;
import com.gc.framework.web.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 库存规格中间 控制层
 * 
 * @author hruiyan
 * @date 2020-11-10
 */
@Slf4j
@Controller
@RequestMapping("/business/inventoryPrice")
public class InventoryPriceController extends BaseController {
    private String prefix = "business/inventoryPrice";
	
	private final IInventoryPriceService inventoryPriceService;

	private final IInventorySizeService inventorySizeService;

	private final IInventorySizePriceService inventorySizePriceService;

    private final IInventoryInfoService inventoryInfoService;

    private final IInventoryRecordService inventoryRecordService;

	@Autowired
	public InventoryPriceController(IInventoryPriceService inventoryPriceService,
									IInventorySizeService inventorySizeService,
									IInventorySizePriceService inventorySizePriceService,
                                    IInventoryInfoService inventoryInfoService,
									IInventoryRecordService inventoryRecordService) {
		this.inventoryPriceService = inventoryPriceService;
		this.inventorySizeService = inventorySizeService;
		this.inventorySizePriceService = inventorySizePriceService;
        this.inventoryInfoService = inventoryInfoService;
        this.inventoryRecordService = inventoryRecordService;
	}

	/**
	*  列表页
	*/
	@RequiresPermissions("business:inventoryPrice:view")
	@GetMapping
	public String inventoryPrice(){
	    return prefix + "/inventoryPrice";
	}

	/**
	 * 新增页
	 */
	@GetMapping("/add/{inventoryId}")
	public String add(ModelMap modelMap,@PathVariable("inventoryId") Long inventoryId){
		InventorySize inventorySize = new InventorySize();
		inventorySize.setAttrId(getAttrId());
		List<InventorySize> inventorySizeList = inventorySizeService.list(inventorySize);
		modelMap.put("inventorySizeList",inventorySizeList);
		modelMap.put("inventoryId",inventoryId);
		return prefix + "/add";
	}

	/**
	 * 编辑页
	 */
	@GetMapping("/edit/{inventoryPriceId}")
	public String edit(@PathVariable("inventoryPriceId") Long inventoryPriceId, ModelMap mmap){
		InventoryPrice inventoryPrice = inventoryPriceService.getById(inventoryPriceId);
		mmap.put("inventoryPrice", inventoryPrice);
		InventorySize inventorySize = new InventorySize();
		inventorySize.setAttrId(getAttrId());
        List<InventorySize> inventorySizeList = inventorySizeService.list(inventorySize);
        mmap.put("inventorySizeList",inventorySizeList);
		return prefix + "/edit";
	}
	
	/**
	 * 查询库存规格中间列表
	 */
	@RequiresPermissions("business:inventoryPrice:list")
	@PostMapping("/list")
	@ResponseBody
	public Result list(InventoryPrice inventoryPrice){
		startPage();
        List<InventoryPrice> list = inventoryPriceService.list(inventoryPrice);
		return Result.success(getDataTable(list));
	}

	/**
	 * 新增保存库存规格中间
	 */
	@RequiresPermissions("business:inventoryPrice:add")
	@Log(title = "库存规格中间", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Result addSave(InventoryPrice inventoryPrice){
		if (inventoryPrice.getSizeId() == null && inventoryPrice.getPriceId() == null){
			return Result.failed("规格或规格值ID为空");
		}
		InventorySize inventorySize = inventorySizeService.getById(inventoryPrice.getSizeId());
		InventorySizePrice inventorySizePrice = inventorySizePriceService.getById(inventoryPrice.getPriceId());
		if (inventorySize == null && inventorySizePrice == null){
			return Result.failed("规格或规格值不存在");
		}
		inventoryPriceService.addSave(inventoryPrice,inventorySize,inventorySizePrice);
        return Result.success();
	}

	/**
	 * 修改保存库存规格中间
	 */
	@RequiresPermissions("business:inventoryPrice:edit")
	@Log(title = "库存规格中间", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Result editSave(InventoryPrice inventoryPrice){
		inventoryPrice.setUpdateBy(ShiroUtils.getSysUser().getUserName());
		inventoryPrice.setUpdateTime(DateUtil.date());
		//修改入库数据,重新计算总库存数及总价格,并修改入库记录
		if (StringUtils.isNotEmpty(inventoryPrice.getItemNum()) || StringUtils.isNotEmpty(inventoryPrice.getItemSum())){
			//修入库记录数据
			InventoryRecord inventoryRecord = inventoryRecordService.getById(inventoryPrice.getRecordId());
			//重新计算剩余数量
			String remainMum = "";
			//计算修改相差数据
			int moneySub = Integer.parseInt(MoneyUtils.moneySub(inventoryPrice.getItemNum(), inventoryRecord.getItemNum()));
			if (moneySub > 0){//增加了
				remainMum = MoneyUtils.moneyAdd(inventoryRecord.getRemainNum(),moneySub+"");
			}else {//减少了
				remainMum = MoneyUtils.moneySub(inventoryRecord.getRemainNum(),moneySub+"");
			}
			inventoryRecord.setRemainNum(remainMum);
			inventoryRecord.setItemNum(inventoryPrice.getItemNum());
			inventoryRecordService.updateById(inventoryRecord);
		}
		inventoryPriceService.updateById(inventoryPrice);
		InventoryInfo inventoryInfo = inventoryInfoService.getById(inventoryPrice.getInventoryId());
		//修改库存数量和金额
		List<InventoryPrice> inventoryPriceList = inventoryPriceService.getByInventoryId(inventoryInfo.getInventoryId());
		String itemNumAll = "0";
		String itemSumAll = "0";
		for (InventoryPrice price : inventoryPriceList) {
			itemNumAll = MoneyUtils.moneyAdd(itemNumAll, price.getItemNum());
			//单个规格的所有数量价格
			String itemSumAllItem = MoneyUtils.moneyMul(price.getItemNum(), price.getItemSum());
			itemSumAll = MoneyUtils.moneyAdd(itemSumAll,itemSumAllItem);
		}
		inventoryInfo.setItemNum(itemNumAll);
		inventoryInfo.setItemSum(itemSumAll);
		inventoryInfoService.updateById(inventoryInfo);
		return Result.success();
	}
	
	/**
	 * 删除库存规格中间
	 */
	@RequiresPermissions("business:inventoryPrice:remove")
	@Log(title = "库存规格中间", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
    @Transactional(rollbackFor = Exception.class)
	public Result remove(String ids){
		Long[] longIds = Convert.toLongArray(ids);
		inventoryPriceService.removeAndSub(longIds);
		return Result.success();
	}

	/**
	 * 导出库存规格中间列表
	 */
	@RequiresPermissions("business:inventoryPrice:export")
	@PostMapping("/export")
	@ResponseBody
	public Result export(InventoryPrice inventoryPrice){
		List<InventoryPrice> list = inventoryPriceService.list(inventoryPrice);
		ExcelUtil<InventoryPrice> util = new ExcelUtil<>(InventoryPrice.class);
		util.exportExcel(list, "inventoryPrice");
		return Result.success();
	}
}
